package com.starsky.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
/**
 *@desc: 获取mac地址
 *@author: wangsh
 */
public class MacUtil {

    private static Logger logger = LoggerFactory.getLogger(MacUtil.class);

    public String getMac() {
        String hostAddress = "UnknownHost";
        try {
            if (this.isWindowsOS()) {
                InetAddress address = InetAddress.getLocalHost();
                if (address != null) {
                    hostAddress = address.getHostAddress();
                }
            } else {
                String linuxLocalIp = this.getLinuxLocalIp();
                if (linuxLocalIp != null && !"".equalsIgnoreCase(linuxLocalIp)) {
                    hostAddress = linuxLocalIp;
                }
            }
        } catch (Exception var4) {
            logger.error("获取服务器IP出错");
        }

        return hostAddress;
    }

    private String getLinuxLocalIp() throws SocketException {
        String ip = "";
        Enumeration en = NetworkInterface.getNetworkInterfaces();

        while (true) {
            NetworkInterface intf;
            String name;
            do {
                do {
                    if (!en.hasMoreElements()) {
                        return ip;
                    }
                    intf = (NetworkInterface) en.nextElement();
                    name = intf.getName();
                } while (name.contains("docker"));
            } while (name.contains("lo"));

            Enumeration enumIpAddr = intf.getInetAddresses();
            while (enumIpAddr.hasMoreElements()) {
                InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    String ipaddress = inetAddress.getHostAddress();
                    if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                        ip = ipaddress;
                    }
                }
            }
        }
    }

    private boolean isWindowsOS() {
        boolean isWindowsOS = false;
        String osName = System.getProperty("os.name");
        if (osName.toLowerCase().contains("windows")) {
            isWindowsOS = true;
        }

        return isWindowsOS;
    }
}
